import { useState } from 'react';
import { getItemName } from '../constants/items';

interface ItemImageProps {
  itemId: number;
  className?: string;
}

export function ItemImage({ itemId, className = "w-6 h-4" }: ItemImageProps) {
  const [currentUrlIndex, setCurrentUrlIndex] = useState(0);
  const [showFallback, setShowFallback] = useState(false);
  
  const itemName = getItemName(itemId);
  
  if (!itemName || showFallback) {
    return (
      <div className={`${className} bg-gray-400 rounded text-xs flex items-center justify-center text-white`}>
        {itemId}
      </div>
    );
  }
  
  const cdnUrls = [
    `https://steamcdn-a.akamaihd.net/apps/dota2/images/items/${itemName}_lg.png`,
    `https://cdn.cloudflare.steamstatic.com/apps/dota2/images/items/${itemName}_lg.png`,
    `https://cdn.dota2.com/apps/dota2/images/items/${itemName}_lg.png`
  ];
  
  const handleImageError = () => {
    if (currentUrlIndex < cdnUrls.length - 1) {
      setCurrentUrlIndex(currentUrlIndex + 1);
    } else {
      setShowFallback(true);
    }
  };
  
  return (
    <img
      src={cdnUrls[currentUrlIndex]}
      alt={itemName}
      className={`${className} object-cover rounded`}
      onError={handleImageError}
      loading="lazy"
    />
  );
}

export default ItemImage;